#include <QFile>
#include "RecentFiles.h"
#include "RecentFilesIONull.h"

const int RecentFiles::MaxNumFiles = 5;

RecentFiles::RecentFiles(QObject *parent) :
    QObject(parent), m_recentFilesIO(new RecentFilesIONull)
{
}

RecentFiles::~RecentFiles()
{
    delete m_recentFilesIO;
}

RecentFiles::RecentFiles(const RecentFiles& recentFiles) :
        QObject(recentFiles.parent())
{
    m_recentFileNames = recentFiles.m_recentFileNames;
    m_recentFilesIO = recentFiles.m_recentFilesIO->clone();
}

RecentFiles& RecentFiles::operator=(const RecentFiles& rhs)
{
    if (m_recentFilesIO)
        delete m_recentFilesIO;
    m_recentFileNames = rhs.m_recentFileNames;
    m_recentFilesIO = rhs.m_recentFilesIO->clone();
    return *this;
}

void RecentFiles::add(const QString& filename)
{
    int location = m_recentFileNames.indexOf(filename);

    if (location > 0)
    {
        // Exists already so promote it to the front.
        m_recentFileNames.move(location, 0);
    }
    else if (location != 0)
    {
        if (m_recentFileNames.count() == MaxNumFiles)
            m_recentFileNames.removeLast();
        m_recentFileNames.push_front(filename);
    }
}

void RecentFiles::clear()
{
    m_recentFileNames.clear();
}

int RecentFiles::count() const
{
    return m_recentFileNames.size();
}

void RecentFiles::existentialCheck()
{
    QStringList deletions;

    foreach (QString filename, m_recentFileNames)
    {
        if (!QFile::exists(filename))
        {
            deletions.push_front(filename);
        }
    }

    foreach (QString filename, deletions)
    {
        m_recentFileNames.removeAll(filename);
    }
}

QString RecentFiles::filename(int i) const
{
    return m_recentFileNames.at(i);
}

const QStringList& RecentFiles::list() const
{
    return m_recentFileNames;
}

int RecentFiles::maxNumRecentFiles() const
{
    return MaxNumFiles;
}

void RecentFiles::read()
{
    m_recentFilesIO->read(*this);
}

void RecentFiles::remove(const QString& filename)
{
    m_recentFileNames.removeAll(filename);
}

void RecentFiles::setIO(RecentFilesIO *recentFilesIO)
{
    if (recentFilesIO && m_recentFilesIO)
    {
        delete m_recentFilesIO;
        m_recentFilesIO = recentFilesIO->clone();
    }
}

void RecentFiles::setList(const QStringList& recentFileNames)
{
    m_recentFileNames = recentFileNames;
}

void RecentFiles::setMostRecent(const QString& filename)
{
    int location = m_recentFileNames.indexOf(filename);

    if (location >= 0)
        m_recentFileNames.move(location, 0);
}

void RecentFiles::write()
{
    m_recentFilesIO->write(*this);
}
